package com.flux.ui.activity

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.AsyncTask
import com.flux.utils.ImageUtil

import com.flux.utils.LogUtil

import java.io.BufferedInputStream
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL

/**
 * Created by Administrator on 2016/10/20.
 */
class SaveImageAs(private val afterSave: (uri: Uri) -> Unit) : AsyncTask<String, Any, Bitmap>() {

    private fun getBitmap(urlpath: String): Bitmap? {

        var map: Bitmap? = null
        try {
            val iconUrl = URL(urlpath)
            val conn = iconUrl.openConnection()
            val http = conn as HttpURLConnection

            val length = http.contentLength

            conn.connect()
            // 获得图像的字符流
            val `is` = conn.getInputStream()
            val bis = BufferedInputStream(`is`, length)
            map = BitmapFactory.decodeStream(bis)
            bis.close()
            `is`.close()// 关闭流
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return map
    }

    override fun doInBackground(params: Array<String>): Bitmap? {
        return getBitmap(params[0])
    }

    override fun onPostExecute(bitmap: Bitmap?) {
        super.onPostExecute(bitmap)
        if (bitmap == null) {
            LogUtil.i("图片保存" + "Bitmap==null")
        } else {
            LogUtil.i("图片保存" + "Bitma!=null")
            afterSave(ImageUtil.saveImageToGallery(bitmap))
        }
    }
}
